package com.helmlabs.grouper.search.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class SearchServiceImpl implements SearchService {

	public List<Map> search(String query) {
		List documents = new ArrayList();
		try {
			Directory directory = FSDirectory.getDirectory("c:/helmlabs/index");
			IndexSearcher isearcher = new IndexSearcher(directory);
			QueryParser parser = new QueryParser("general", new StandardAnalyzer());
			Query q = parser.parse(query);
			Hits hits = isearcher.search(q);
			for (int i=0; i<hits.length();i++){
				Document hitDoc = hits.doc(i);
				Map resultMap = new HashMap();
				resultMap.put("score", hits.score(i));				
				for (Iterator<Field> fieldsItr = hitDoc.getFields().iterator(); fieldsItr.hasNext();){
					Field field = fieldsItr.next();
					resultMap.put(field.name(), field.stringValue());
				}
//				System.out.println("found the hit " + hitDoc.get("id"));
//				System.out.println("found the hit has " + hitDoc.get("type"));
				documents.add(resultMap);
			}
			isearcher.close();
			directory.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return documents;
	}
	
	

}
